import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:mall/core/models/store_total.dart';
import 'package:mall/core/providers/pages/mine/manage/store_manage_model.dart';
import 'package:mall/core/providers/view_model.dart';
import 'package:mall/screens/group/group_history_screen.dart';
import 'package:mall/screens/manage/bank_page.dart';
import 'package:mall/screens/manage/business_type_screen.dart';
import 'package:mall/screens/manage/withdraw_page.dart';
import 'package:mall/screens/account/account_page.dart';
import 'package:mall/screens/point/point_exchange_screen.dart';
import 'package:mall/screens/order/order_page.dart';
import 'package:mall/components/mine_func_button.dart';
import 'package:mall/components/mine_order_button.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mall/screens/point/point_transfer_screen.dart';
import 'package:provider/provider.dart';

class StoreManagePage extends StatelessWidget {
  static const routeName = '/StoreManagePage';
  final int args;

  StoreManagePage({
    Key key,
    this.args,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => StoreManageModel(Provider.of(context, listen: false), args),
      child: Scaffold(
        appBar: AppBar(
          title: Text('店铺管理'),
        ),
        body: Consumer<StoreManageModel>(
          builder: (context, model, child) {
            switch (model.viewState) {
              case ViewState.busy:
                return Center(
                  child: CircularProgressIndicator(),
                );
              case ViewState.error:
                return Center(
                  child: Text(model.errorMessage),
                );
              case ViewState.success:
                return _BodyWidget();
              default:
                return Container();
            }
          },
        ),
      ),
    );
  }
}

class _BodyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CustomScrollView(
      slivers: <Widget>[
        _HeaderWidget(),
        SliverToBoxAdapter(
          child: Container(
            margin: EdgeInsets.all(8.w),
            child: Material(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  _BottomTitleWidget(),
                  _BottomFuncWidget(),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }
}

class _HeaderWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SliverToBoxAdapter(
      child: Stack(
        alignment: Alignment.bottomCenter,
        children: <Widget>[
          Container(
            // decoration: BoxDecoration(
            //   color: Theme.of(context).primaryColor,
            // ),
            height: 212,
            margin: EdgeInsets.only(bottom: 23),
          ),
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(8.w),
            ),
            height: 200,
            margin: EdgeInsets.symmetric(horizontal: 8.w),
          ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 36),
            height: 212 - 6.0,
            margin: EdgeInsets.only(bottom: 23),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                _HeaderItemOneWidget(),
                _HeaderItemTwoWidget(),
                Divider(height: 1),
                _HeaderItemThreeWidget(),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

class _HeaderItemOneWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    StoreManageModel model = Provider.of(context, listen: false);
    StoreTotal storeTotal = model.storeTotal;
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.end,
      children: <Widget>[
        CircleAvatar(
          radius: 35,
          backgroundImage: CachedNetworkImageProvider(storeTotal.logoUrl ?? ''),
        ),
        Expanded(
          child: Container(
            margin: EdgeInsets.symmetric(horizontal: 6),
            child: Text(
              '${storeTotal.storeName}  ',
              style: TextStyle(color: Colors.amber, fontSize: 25, fontWeight: FontWeight.bold),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ),
        Container(
          decoration: BoxDecoration(
            color: Colors.white,
            border: Border.all(color: Colors.amber),
            borderRadius: BorderRadius.all(Radius.circular(8)),
          ),
          padding: EdgeInsets.symmetric(vertical: 4, horizontal: 8),
          child: Text(
            '${storeTotal.businessDescr}',
            style: TextStyle(color: Colors.amber, fontSize: 10),
          ),
        )
      ],
    );
  }
}

class _HeaderItemTwoWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    StoreManageModel model = Provider.of(context, listen: false);
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        RichText(
          text: TextSpan(
            text: '店铺级别：',
            style: TextStyle(color: Colors.black, fontSize: 12),
            children: [TextSpan(text: '${model.storeTotal.storeLevelName ?? ""}')],
          ),
        ),
        RichText(
          text: TextSpan(
            text: '店铺ID：',
            style: TextStyle(color: Colors.black, fontSize: 12),
            children: [TextSpan(text: '${model.storeTotal.storeId}')],
          ),
        ),
      ],
    );
  }
}

/// 订单状态分类
class _HeaderItemThreeWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    StoreManageModel model = Provider.of(context, listen: false);
    StoreTotal storeTotal = model.storeTotal;
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        MineOrderButton(
          name: 'assets/images/mine/ic_pending_all.png',
          title: '全部订单',
          onTap: () {
            _onOrderClicked(context, 0);
          },
        ),
        MineOrderButton(
          name: 'assets/images/mine/ic_pending_pay.png',
          title: '待付款',
          badge: storeTotal.total('PAYING_ORDER_TOTAL'),
          onTap: () {
            _onOrderClicked(context, 1);
          },
        ),
        MineOrderButton(
          name: 'assets/images/mine/ic_pending_send.png',
          title: '待发货',
          badge: storeTotal.total('SENDING_ORDER_TOTAL'),
          onTap: () {
            _onOrderClicked(context, 2);
          },
        ),
        MineOrderButton(
          name: 'assets/images/mine/ic_pending_receive.png',
          title: '待收货',
          badge: storeTotal.total('RECEIPTING_ORDER_TOTAL'),
          onTap: () {
            _onOrderClicked(context, 3);
          },
        ),
      ],
    );
  }

  void _onOrderClicked(BuildContext context, int index) {
    StoreManageModel model = Provider.of(context, listen: false);
    final storeId = model.storeId;
    Navigator.of(context).pushNamed(
      OrderPage.routeName,
      arguments: OrderPageArgs(storeId, index),
    );
  }
}

class _BottomTitleWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(16),
      child: Text('常用功能', style: TextStyle(color: Colors.black87)),
    );
  }
}

/// 底部功能模块
class _BottomFuncWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    StoreManageModel model = Provider.of(context, listen: false);
    return GridView.extent(
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      padding: EdgeInsets.symmetric(horizontal: 4),
      maxCrossAxisExtent: (375 - 8) / 3,
      childAspectRatio: 1.125,
      children: <Widget>[
        MineFuncButton(
          name: 'assets/images/store/ic_func_bank.png',
          title: '银行账户',
          onTap: () => Navigator.of(context).pushNamed(BankPage.routeName),
        ),
        MineFuncButton(
          name: 'assets/images/store/ic_func_business.png',
          title: '业务申请',
          onTap: () => Navigator.of(context).pushNamed(BusinessTypeScreen.routeName),
        ),
        if (!model.storeTotal.icpMode)
          MineFuncButton(
            name: 'assets/images/store/ic_func_withdraw.png',
            title: '店铺结算',
            onTap: () => Navigator.of(context).pushNamed(
              WithdrawPage.routeName,
              arguments: model.storeId,
            ),
          ),
        MineFuncButton(
          name: 'assets/images/store/ic_func_score.png',
          title: '店铺积分',
          onTap: () => Navigator.of(context).pushNamed(AccountPage.routeName, arguments: 'store'),
        ),
        if (model.storeTotal.displayExchangeCoin)
          MineFuncButton(
            name: 'assets/images/store/ic_func_ad.png',
            title: '积分兑换',
            onTap: () {
              _pointsExchange(context);
            },
          ),
        if (model.storeTotal.displayTransferCoin)
          MineFuncButton(
            name: 'assets/images/store/ic_func_transfer.png',
            title: '积分转赠',
            onTap: () => Navigator.of(context).pushNamed(PointTransferScreen.routeName),
          ),
        MineFuncButton(
          name: 'assets/images/store/ic_func_qr_code.png',
          title: '拼购历史',
          onTap: () {
            _groupPurchaseHistory(context);
          },
        ),
      ],
    );
  }

  /// 积分兑换
  void _pointsExchange(BuildContext context) {
    Navigator.of(context).pushNamed(PointExchangeScreen.routeName);
  }

  /// 拼购历史
  void _groupPurchaseHistory(BuildContext context) {
    Navigator.of(context).pushNamed(GroupHistoryScreen.routeName);
  }
}
